<?php

namespace app\index\controller;

use tests\thinkphp\library\think\logTest;
use think\Controller;
use think\Db;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    /**
     * 回调处理：
     * */
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {

            //接收附加数据
            $json_attach = $data['attach'];
            $attach_arr = json_decode($json_attach, true);

            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $pay_time = Db::name('order')->where(['order_sn' => $order_sn])->value('pay_time');

            if ($pay_time == 0) {
                Db::startTrans();
                try {
                    $this->doServiceOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 开通服务订单支付成功处理业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doServiceOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['order_sn' => $order_sn])->find();

        $service_info = Db::name('service')->where(['id' => $order_info['service_id']])->find();

        $order_id = $order_info['id'];
        $user_id = $order_info['user_id'];
        $pay_price = $order_info['pay_price'];
        $up_user_id = Db::name('user')->where(['id' => $user_id])->value('up_user_id');

        $time = time();

        Db::startTrans();
        try {
            // 1：修改订单信息
            $order_data = [
                'days' => $service_info['days'],
                'status' => 2,
                'is_pay' => 1,
                'pay_time' => $time
            ];
            Db::name('order')->where(['id' => $order_id])->update($order_data);

            // 2：增加企业服务天数
            if ($service_info['days'] > 0) {
                $company_info = Db::name('company')->where(['user_id' => $user_id])->find();
                if (empty($company_info)) {
                    Db::rollback();
                    return false;
                }

                $company_data = [
                    'update_time' => $time
                ];
                $inc_time = $service_info['days'] * 86400;
                if ($company_info['service_end_time'] > $time) {
                    // 续费
                    $company_data['service_end_time'] = $company_info['service_end_time'] + $inc_time;
                    Db::name('company')->where(['user_id' => $user_id])->update($company_data);
                    Db::name('order')->where(['id' => $order_id])->setField('expire_time', $company_data['service_end_time']);
                } else {
                    // 新开通
                    $company_data['service_end_time'] = $time + $inc_time;
                    Db::name('company')->where(['user_id' => $user_id])->update($company_data);
                }
            }

            // 3：上级用户分佣
            $rate = $service_info['rate'];
            if ($up_user_id > 0 && $rate > 0) {
                // 上级用户的角色
                $user_profit = Db::name('user')->where(['id' => $up_user_id])->value('profit');
                $profit = $pay_price * $rate / 100;
                if ($profit > 0) {
                    Db::name('user')->where('id', $up_user_id)->setInc('profit', $profit);
                    // 4：生成余额记录
                    $profit_log = [
                        'user_id' => $up_user_id,
                        'profit' => $profit,
                        'before' => $user_profit,
                        'after' => $user_profit + $profit,
                        'type' => 2,
                        'remark' => '下级会员下单收益',
                        'link_id' => $order_info['id'],
                        'link_table' => 'order',
                        'create_time' => $time
                    ];
                    Db::name('profit_log')->insert($profit_log);
                }
            }

            // 5：下单用户生成服务通知
            $msg_data = [
                'user_id' => $user_id,
                'order_id' => $order_info['id'],
                'title' => '服务开通成功',
                'content' => '恭喜您，开通'. $service_info['name'] .'企业服务，' . ($company_data['service_end_time'] ? ('服务将在' . date('Y-m-d', $company_data['service_end_time']) . '前有效') : ''),
                'type' => 2,
                'create_time' => $time
            ];
            Db::name('msg')->insert($msg_data);

            Db::commit();
        } catch (\Exception $e) {
            file_put_contents(RUNTIME_PATH . 'order.txt', $e->getMessage() . PHP_EOL, FILE_APPEND);
            Db::rollback();
        }
    }
}